@echo off
chcp 65001 >nul
title WanKe ERP System Launcher

echo ====================================
echo      WanKe ERP System Launcher
echo ====================================
echo.

:: Set path variables
set JAR_PATH=E:\erp\erp.jar
set NGINX_PATH=E:\erp\nginx-1.27.4
set NGINX_EXE=%NGINX_PATH%\nginx.exe

:: Check if files exist
if not exist "%JAR_PATH%" (
    echo [ERROR] JAR file not found: %JAR_PATH%
    goto :error_exit
)

if not exist "%NGINX_EXE%" (
    echo [ERROR] Nginx executable not found: %NGINX_EXE%
    goto :error_exit
)

:: Check port usage
echo [CHECK] Checking port usage...
netstat -ano | findstr :8080 >nul
if %errorlevel% == 0 (
    echo [WARNING] Port 8080 is already in use
    echo [INFO] You may need to stop existing services first
)

netstat -ano | findstr :3100 >nul
if %errorlevel% == 0 (
    echo [WARNING] Port 3100 is already in use
)

:: Start Nginx service first
echo [START] Starting Nginx service...
cd /d "%NGINX_PATH%"
start "WanKe ERP Frontend" "%NGINX_EXE%"
if %errorlevel% neq 0 (
    echo [ERROR] Failed to start Nginx service
    goto :error_exit
)

:: Wait for Nginx to start
timeout /t 3 /nobreak >nul

:: Check Nginx status
tasklist | findstr nginx >nul
if %errorlevel% neq 0 (
    echo [ERROR] Nginx service failed to start properly
    goto :error_exit
) else (
    echo [SUCCESS] Nginx service started successfully
)

:: Open browser automatically
echo [START] Opening browser...
start http://192.168.161.188:3100

echo.
echo ====================================
echo WanKe ERP System Starting...
echo Frontend: http://192.168.161.188:3100
echo Backend: http://192.168.161.188:8080
echo ====================================
echo.
echo [INFO] Starting backend service in current window...
echo [INFO] You will see the application logs below.
echo [INFO] Press Ctrl+C to stop the backend service.
echo.

:: Change window title to show backend status
title WanKe ERP Backend - Running

:: Start backend service in current window (this will keep the window open)
java -jar "%JAR_PATH%" --spring.profiles.active=dev

:: This section will only execute if the JAR exits
echo.
echo ====================================
echo Backend service has stopped.
echo ====================================
echo.
echo Press any key to close this window...
pause >nul
exit /b 0

:error_exit
echo.
echo ====================================
echo WanKe ERP System Start Failed!
echo ====================================
echo.
echo Press any key to close this window...
pause >nul
exit /b 1
